/* eslint-disable no-unused-vars */
import { reqCartList, reqDeleteCartById, reqUpdateCheckedById } from '@/api'

const state = {
  cartList: [],
}
const mutations = {
  GETCARTLIST(state, cartList) {
    state.cartList = cartList
  }
}
const actions = { 
  async getCartList({ commit }) {
    let result = await reqCartList();
    if (result.code == 200) {  
      commit('GETCARTLIST', result.data)
    }
  },
  async reqDeleteCartBySkuId({ commit }, skuId) {
    let result = await reqDeleteCartById(skuId)
    if (result.code == 200) {
      return "ok"
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  async updateCheckedById({commit}, {skuId, isChecked}) {
    let result = await reqUpdateCheckedById(skuId, isChecked);
    if (result.code == 200) {
      return "ok"
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  // 删除购物车中全部勾选商品
  deleteAllCheckedCart({dispatch, getters}) {
    let PromiseAll = []
    getters.cartList.cartInfoList.forEach(item => {
      if (item.isChecked) {
        let promise = item.isChecked == 1 ? dispatch('reqDeleteCartBySkuId', item.skuId) : ''
        // 将每一次返回的Promise添加到数组中
        PromiseAll.push(promise)
      }
    })
    // 所有的promise都成功，则返回成功，出现一个失败，则失败
    return Promise.all(PromiseAll);
  },
  // 修改全部产品勾选状态
  updateAllCheckedCart({dispatch, state}, isChecked) {
    let PromiseAll = []
    state.cartList[0].cartInfoList.forEach(item => {
      let promise = dispatch('updateCheckedById', {skuId: item.skuId, isChecked})
      PromiseAll.push(promise)
    })
    return Promise.all(PromiseAll);
  }
}
const getters = {
  cartList(state) {
    return state.cartList[0] || {}
  },
}

export default ({
  state,
  mutations,
  actions,
  getters
})

